package jsu.blogger.Interceptor;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jsu.blogger.util.DataProcessingUtil;
import org.jetbrains.annotations.NotNull;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import java.util.Map;

@Component
public class PostInterceptor implements HandlerInterceptor {
    private static final Logger logger = LoggerFactory.getLogger(PostInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 记录请求信息
        logger.info("Incoming request: {} {}", request.getMethod(), request.getRequestURI());
        if(request.getRequestURI().contains("/post/getRecommendedBlogs")) {
            return processUid(request) && isValidOffsetAndCount(request);
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 在请求处理后执行的逻辑
        logger.info("Post handle method called for request: {}", request.getRequestURI());
        // 可以在这里修改 ModelAndView 以添加额外的数据
        if (modelAndView != null) {
            modelAndView.addObject("interceptorMessage", "This message is added by PostInterceptor");
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 请求完成后的逻辑
        logger.info("Completed request: {} with status: {}", request.getRequestURI(), response.getStatus());
        if (ex != null) {
            logger.error("Exception occurred: ", ex);
        }
    }
    //检查uid是否存在并传送到控制器
    private boolean processUid(HttpServletRequest request) {
        // 获取请求头部信息
        String uidStr = request.getHeader("uid");
        try {
            // 将 uid 转换为 long 类型
            if (uidStr != null) {
                long uid = Long.parseLong(uidStr);
                // 将 uid 存储在请求属性中
                request.setAttribute("uid", uid);
            }
            //成功转换或者没有传uid
            return true;
        } catch (NumberFormatException e) {
            logger.error("Post拦截器uid转换失败 原因: {}", e.getMessage());
            return false;//转换失败
        }
    }
    private boolean isValidOffsetAndCount(HttpServletRequest request) {
        try {
            Map<String,Object> requestBody = (Map<String, Object>) request.getAttribute("requestBody");
            Long count= DataProcessingUtil.getLongValue(requestBody,"count",0L);
            Long offset= DataProcessingUtil.getLongValue(requestBody,"offset",0L);
            if( count > 0 &&offset>=0){
                request.setAttribute("count", count);
                request.setAttribute("offset", offset);
                return true;
            }
        }catch (Exception e){
            logger.error("Post拦截器处理数据异常 原因"+e);
        }
        return false;
    }
    private boolean userHasPermission(HttpServletRequest request) {
        // 在这里实现您的权限检查逻辑
        // 返回 true 表示有权限，返回 false 表示没有权限
        return true; // 仅为示例，实际逻辑根据需要实现
    }
}
